package com.jingdong.service.impl;

import com.jingdong.repository.BaoGaoDetailRepository;
import com.jingdong.service.BaoGaoDetailCategoryService;
import com.jingdong.pojo.BaoGaoDetail;
import com.mysql.jdbc.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.lang.invoke.MethodHandles;
import java.util.List;
@Service
@Transactional(rollbackFor = Exception.class)
@CacheConfig
public class BaoGaoDetailCategoryServiceImpl implements BaoGaoDetailCategoryService {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    @Autowired
    private BaoGaoDetailRepository baoGaoDetailRepository;


    @Override
    @Cacheable(value = "baogao", key = "#a0")
    public Page<BaoGaoDetail> findALLByLikeTitle(Integer page, Integer size, BaoGaoDetail baoGaoDetail) throws Exception {
        try {
            String title = baoGaoDetail.getTitle();
            Specification<BaoGaoDetail> specification = (Specification<BaoGaoDetail>) (root, query, criteriaBuilder) -> {
                Path<String> _title = root.get("title");
                Predicate _key = criteriaBuilder.like(_title, "%" + title + "%");
                return criteriaBuilder.and(_key);
            };
            Sort sort = new Sort(Sort.Direction.DESC, "id");
            Pageable pageable = new PageRequest(page - 1, size, sort);
            return baoGaoDetailRepository.findAll(specification, pageable);

        }catch (Exception e){
            logger.error(e.getLocalizedMessage());
            return null;
        }
    }



    @Override
    @Cacheable(value = "baogao", key = "#a0")
    public Page<BaoGaoDetail> findAll(Integer page, Integer size) {
        try {
            Pageable pageable = new PageRequest(page, size, Sort.Direction.ASC, "id");
            return baoGaoDetailRepository.findAll(pageable);
        }catch (Exception e){
            logger.error(e.getLocalizedMessage());
            return null;
        }
    }
}
